from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy import String, Integer, SmallInteger, ForeignKey, Boolean
from ..utils.models import BaseModel
from ..utils.parse import build_tree_nodes


class User(BaseModel):
    __tablename__ = "user"

    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    username: Mapped[str] = mapped_column(String(32), unique=True)
    mobile: Mapped[str] = mapped_column(String(11), comment="手机号")
    email: Mapped[str] = mapped_column(String(32))
    password: Mapped[str] = mapped_column(String(64))
    avatar: Mapped[str] = mapped_column(String(256))
    gender: Mapped[int] = mapped_column(SmallInteger, default=1)
    role_id: Mapped[int] = mapped_column(ForeignKey("role.id"), nullable=True)
    is_superadmin: Mapped[bool] = mapped_column(Boolean, default=False)
    role: Mapped["Role"] = relationship(back_populates="user")

    @property
    def info(self):
        return {
            "id": self.id,
            "username": self.username,
            "mobile": self.mobile,
            "email": self.email,
            "avatar": self.avatar,
            "gender": self.gender
        }

    @property
    def menus(self):
        """
        获取用户菜单
        menu_tree element

        {
                "id":1,
                "identity":"user",
                "meta":{
                    "frameSrc":null,
                    "hiddenTag":false,
                    "icon":"user",
                    "keepAlive":false,
                    "showLink":false,
                    "title":"用户管理",
                    "auths":[]
                },
                "name":"menu",
                "parent_id":null,
                "path":"/system/user"
            }

        :return:  menu_tree
        """
        menu_nodes = []
        role_menu_dict = {menu.id: menu.to_dict for menu in self.role.menu}
        permissions_dict = {permission.menu_id: permission.key for permission in self.role.permission}

        for menu_id, menu_dic in role_menu_dict.items():
            if menu_id in permissions_dict:
                menu_dic["meta"].setdefault("auths", []).append(permissions_dict[menu_id])
            """ 获取用户的按钮权限 将按钮权限存放带对应菜单的auths（type list）中 """
            menu_nodes.append(menu_dic)
        menu_tree = build_tree_nodes(menu_nodes)
        return menu_tree
